from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info.models import User, News, Category
from info.modules.index import index_blu

# 12)创建首页视图函数
from info.utils.common import login_user_info
from info.utils.response_code import RET


@index_blu.route('/', methods=['GET', 'POST'])
@login_user_info
def index():
    from info import redis_store
    # 6)设置redis是否能够储存数据
    # redis_store.set('name', 'zhang')
    """
    1.获取到新闻排行榜的数据
    2.将获取到的数据变成字典
    3.将数据加载到页面上
    """
    # 排行榜
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据获取失败')

    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_dict())


    # 新闻分类
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())


    # 拼接数据,渲染到页面中
    data = {
        # 如果user有值返回左边内容, 如果没有值返回右边内容
        "user_info": g.user.to_dict() if g.user else "",
        'click_news_list': click_news_list,
        'categories_list': categories_list
    }

    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def get_web_lofo():
    return current_app.send_static_file("news/favicon.ico")


# 请求参数  参数1 cid  参数2 页码 参数3: 每页显示数量
# 请求方式 get
@index_blu.route('/newslist')
def newslist():
    """
    1.获取参数
    2.将页码和每页转成int类型
    #  filters=[]   if cid != '1'
    3.News.quert.filter().order_by(News.asdasasd.desc()).paginate(page,getshu,False)
    4. paginate.pages   paginate.page   paginate.items
    :return:
    data={
    }
    return(tol=pages,newsList=items)
    """
    # 1.获取参数
    category_id = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)
    # 2.将页码和每页转成int类型
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3.判断分类是否为最新
    filters = []
    if category_id != 1:
        filters.append(News.category_id == category_id)
    try:
        # 查询分页,获取到总页数,当年页数,每页个数
        paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page, per_page, False)
        news = paginate.items
        pages = paginate.pages
        page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')
    # 4.将查询到的所有数据转成字典
    news_list = []
    for new in news:
        news_list.append(new.to_dict())
    return jsonify(errno=RET.OK, errmsg='OK', totalPage=pages, cid=category_id, page=page, newsList=news_list)
